package com.fintek.mx.mxMarket.ui.home

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.SystemClock
import android.view.LayoutInflater
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.ThreadUtils
import com.blankj.utilcode.util.ToastUtils
import com.fintek.mx.mxMarket.R
import com.fintek.mx.mxMarket.base.BaseActivity
import com.fintek.mx.mxMarket.base.getFragment
import com.fintek.mx.mxMarket.databinding.ActivityHomeBinding
import com.fintek.mx.mxMarket.ui.order.OrderFragment
import com.fintek.mx.mxMarket.ui.user.UserFragment
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.CommonPagerTitleView
import kotlin.math.abs

class HomeActivity : BaseActivity<BaseViewModel, ActivityHomeBinding>() {

    private val fragmentList = mutableListOf<Fragment>()

    companion object {
        private val TAB_RES_SELECTED = arrayOf(
            R.mipmap.icon_home_home_selected, R.mipmap.icon_home_search_selected,
            R.mipmap.icon_home_user_selected
        )
        private val TAB_RES_NORMAL = arrayOf(
            R.mipmap.icon_home_home_normal, R.mipmap.icon_home_search_normal,
            R.mipmap.icon_home_user_normal
        )
    }

    override fun initView(savedInstanceState: Bundle?) {
        fragmentList.clear()
        supportFragmentManager.let {
            fragmentList.add(it.getFragment(HomeFragment::class.java))
            fragmentList.add(it.getFragment(OrderFragment::class.java))
            fragmentList.add(it.getFragment(UserFragment::class.java))
        }
        addFragments()
        showFragments(0)
        val commonNavigator = CommonNavigator(this)
        commonNavigator.isAdjustMode = true
        commonNavigator.adapter = object : CommonNavigatorAdapter() {
            override fun getCount(): Int {
                return fragmentList.size
            }

            override fun getTitleView(context: Context?, index: Int): IPagerTitleView {
                return CommonPagerTitleView(context).also {
                    val customLayout = LayoutInflater.from(context)
                        .inflate(R.layout.simple_pager_title_layout, it, false)
                    val titleImg: ImageView = customLayout.findViewById(R.id.title_img)
//                    val titleText: TextView = customLayout.findViewById(R.id.title_text)

//                    titleText.text = TAB_TEXT[index]
                    titleImg.setImageResource(TAB_RES_NORMAL[index])

                    it.setContentView(customLayout)
                    it.onPagerTitleChangeListener = object : CommonPagerTitleView.OnPagerTitleChangeListener {
                        override fun onSelected(index: Int, totalCount: Int) {
                            titleImg.setImageResource(TAB_RES_SELECTED[index])
//                            titleText.setTextColor(ColorUtils.getColor(R.color.theme_color))
                        }

                        override fun onDeselected(index: Int, totalCount: Int) {
                            titleImg.setImageResource(TAB_RES_NORMAL[index])
//                            titleText.setTextColor(ColorUtils.getColor(R.color.black63_a40))
                        }

                        override fun onLeave(
                            index: Int,
                            totalCount: Int,
                            leavePercent: Float,
                            leftToRight: Boolean
                        ) {

                        }

                        override fun onEnter(
                            index: Int,
                            totalCount: Int,
                            enterPercent: Float,
                            leftToRight: Boolean
                        ) {

                        }

                    }
                    it.setOnClickListener {
                        showFragments(index)
                        repeat(fragmentList.size) { repeat ->
                            if (index == repeat) {
                                commonNavigator.onPageSelected(index)
                            } else {
                                commonNavigator.onDeselected(repeat, fragmentList.size)
                            }
                        }
                    }
                }
            }

            override fun getIndicator(context: Context?): IPagerIndicator? {
                return null
            }
        }

        mDatabind.homeTab.navigator = commonNavigator

        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                val nowMillis = SystemClock.elapsedRealtime()
                if (abs(sLastClickMillis - nowMillis) < 2000) {
                    finish()
                } else {
                    ToastUtils.showShort("再按一次退出")
                    sLastClickMillis = nowMillis
                }
            }
        })
    }

    private var sLastClickMillis: Long = 0

    private fun addFragments() {
        fragmentList.forEach {
            if (!it.isAdded) {
                supportFragmentManager.beginTransaction()
                    .add(R.id.content_layout, it, it.javaClass.name)
                    .hide(it)
                    .commit()
            }
        }
    }

    private fun showFragments(index: Int) {
        for (i in fragmentList.indices) {
            val ft: FragmentTransaction = supportFragmentManager.beginTransaction()
            val fragment: Fragment = fragmentList[i]
            if (i == index) {
                ft.show(fragment)
            } else {
                ft.hide(fragment)
            }
            ft.commit()
        }
    }
}